package com.ruoyi.rsikManage.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.rsikManage.domain.MonitorPoint;
import com.ruoyi.rsikManage.domain.vo.MonitorPointDiagnosisResultVo;
import com.ruoyi.rsikManage.service.JyService;
import com.ruoyi.rsikManage.service.MonitorPointService;
import com.ruoyi.rsikManage.service.VideoDiagnosisService;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RequestMapping("/rsikManage/videoDiagnosis")
@RestController
public class VideoDiagnosisController extends BaseController {

    @Value("${jy.ip}")
    private String JY_IP;
    @Value("${jy.port}")
    private String JY_LOGIN_PORT;
    @Autowired
    VideoDiagnosisService videoDiagnosisService;
    @Autowired
    MonitorPointService monitorPointService;
    @Autowired
    JyService jyService;
    private List<String> diagnosticItems = Arrays.asList("color_cast", "contrast_ratio", "cross_striation", "definition", "freeze", "high_luminance", "jitter", "loss", "low_luminance", "noise", "occlusion", "rolling_stripe", "scene_change", "stripe", "transverse_wave");

    /**
     * 查询历史诊断结果
     * @param param
     * @return
     */
    @PostMapping("selectHistoryDiagnosisResult")
    public TableDataInfo selectHistoryDiagnosisResult(@RequestBody HashMap<String, Object> param) {
        int pageNum = (int) param.getOrDefault("pageNum", 1);
        int pageSize = (int) param.getOrDefault("pageSize", 10);
        PageHelper.startPage(pageNum, pageSize);
        setDiagnosisNodeSet(param);
        List<MonitorPointDiagnosisResultVo> res = videoDiagnosisService.selectHistoryDiagnosisResult(param);
        return getDataTable(res);
    }

    /**
     * 查询最近一次的诊断结果
     * @param param
     * @return
     */
    @PostMapping("selectLastDiagnosisResult")
    public TableDataInfo selectLastDiagnosisResult(@RequestBody HashMap param)
    {
        param.put("page_num", 1);
        param.put("page_size", 99999);
        Integer pageNum = (Integer) param.getOrDefault("pageNum", 1);
        Integer pageSize = (Integer) param.getOrDefault("pageSize", 10);
        setDiagnosisNodeSet(param);
        String monitorDiagnosisResultListJsonStr = jyService.getLastVideoDiagnosisResult(param);
        List<MonitorPointDiagnosisResultVo> resList = filterAndSortDiagnosisResult(monitorDiagnosisResultListJsonStr, param);

        int resListSize = resList.size();
        int total = resListSize;
        int start = (pageNum - 1) * pageSize ;
        if (start > resListSize - 1) {
            start = 0;
        }
        int end = Math.min(start + pageSize, resListSize);
        resList = resList.subList(start, end);

        List<String> monitorIdList = resList.stream()
                .map(MonitorPointDiagnosisResultVo::getApeId)
                .collect(Collectors.toList());

        HashMap<String, MonitorPoint> monitorMap = monitorPointService.selectMonitorMapByList(monitorIdList);

        for (MonitorPointDiagnosisResultVo monitorDiagnosisResult : resList) {
            MonitorPoint monitor = monitorMap.get(monitorDiagnosisResult.getApeId());
            monitorDiagnosisResult.setMonitorPointName(monitor.getName());
            monitorDiagnosisResult.setOwnerApsName(monitor.getOwnerApsName());
            monitorDiagnosisResult.setOwnerApsIp(monitor.getOwnerApsIp());
            monitorDiagnosisResult.setIsOnline(monitor.getIsOnline());
            monitorDiagnosisResult.setModel(monitor.getModel());
            monitorDiagnosisResult.setPictureUrl("http://"+JY_IP+":"+JY_LOGIN_PORT+"/"+monitorDiagnosisResult.getPictureUrl()+"?timestamp=1");
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(resList);
        rspData.setTotal(total);
        return rspData;
    }
    /**
     * 添加方案
     */
    @PostMapping("addVideoDiagnosisScheme")
    public String addVideoDiagnosisScheme(@RequestBody Map param) {
        return jyService.addVideoDiagnosisScheme(param);
    }
    /**
     * 修改方案
     */
    @PutMapping("updateVideoDiagnosisScheme")
    public String updateVideoDiagnosisScheme(@RequestParam String schemeId, @RequestBody Map param) {
        return jyService.updateVideoDiagnosisScheme(schemeId, param);
    }

    /**
     * 分页查询方案列表
     */
    @GetMapping("selectVideoDiagnosisSchemeList")
    public TableDataInfo selectVideoDiagnosisSchemeList(String name, Integer page_num, Integer page_size) {
        String jsonStr = jyService.selectVideoDiagnosisSchemeList(name, page_num, page_size);
        JSONArray jsonArray = JSONObject.parseObject(jsonStr).getJSONObject("data").getJSONArray("data");
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(jsonArray);
        rspData.setTotal(JSONObject.parseObject(jsonStr).getJSONObject("data").getJSONObject("paging").getIntValue("total"));
        return rspData;
    }

    /**
     * 查询单个方案的详情
     */
    @GetMapping("selectVideoDiagnosisScheme/{id}")
    public String selectVideoDiagnosisScheme(@PathVariable String id) {
        return jyService.selectVideoDiagnosisScheme(id);
    }

    /**
     * 删除方案
     */
    @DeleteMapping("deleteVideoDiagnosisScheme")
    public String deleteVideoDiagnosisScheme(@RequestParam String ids) {
        return jyService.deleteVideoDiagnosisSchemes(ids);
    }

    /**
     * 添加预案
     */

    @PostMapping("addVideoDiagnosisPlan")
    public String addVideoDiagnosisPlan(@RequestBody Map param) {
        return jyService.addVideoDiagnosisPlan(param);
    }
    /**
     * 修改预案
     */
    @PutMapping("updateVideoDiagnosisPlan")
    public String updateVideoDiagnosisPlan(@RequestParam String planId, @RequestBody Map param) {
        return jyService.updateVideoDiagnosisPlan(planId, param);
    }

    /**
     * 分页查询预案列表
     */
    @GetMapping("selectVideoDiagnosisPlanList")
    public TableDataInfo selectVideoDiagnosisPlanList(String name, Integer page_num, Integer page_size) {
        String jsonStr = jyService.selectVideoDiagnosisPlanList(name, page_num, page_size);

        JSONArray jsonArray = JSONObject.parseObject(jsonStr).getJSONObject("data").getJSONArray("data");
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(jsonArray);
        rspData.setTotal(JSONObject.parseObject(jsonStr).getJSONObject("data").getJSONObject("paging").getIntValue("total"));

        return rspData;
    }

    /**
     * 查询单个预案详情
     */
    @GetMapping("selectVideoDiagnosisPlan/{id}")
    public String selectVideoDiagnosisPlan(@PathVariable String id) {
        return jyService.selectVideoDiagnosisPlan(id);
    }

    /**
     * 删除预案
     */
    @DeleteMapping("deleteVideoDiagnosisPlan")
    public String deleteVideoDiagnosisPlan(@RequestParam String ids) {
        return jyService.deleteVideoDiagnosisPlans(ids);
    }

    /**
     * 启动/禁用预案
     */
    @PutMapping("updatePlanStatus")
    public String updatePlanStatus(@RequestParam String ids, @RequestParam Integer status) {
        return jyService.updatePlanStatus(ids, status);
    }

    private List<MonitorPointDiagnosisResultVo> filterAndSortDiagnosisResult (String monitorDiagnosisResultListJsonStr, HashMap param)
    {
        JSONArray monitorDiagnosisResultJsonArray = JSONObject.parseObject(monitorDiagnosisResultListJsonStr).getJSONObject("data").getJSONArray("data");

        LinkedList<MonitorPointDiagnosisResultVo> res = new LinkedList<>();
        Map<Integer, String> videoDiagnosisDicMap = new HashMap<Integer, String>() {{
            put(1, "正常");
            put(2, "预警");
            put(3, "报警");
            put(4, "未检测");
            put(5, "检测失败");
        }};
        HashMap<Integer, String> diagnosisResultDicMap = new HashMap<Integer, String>() {{
            put(1, "正常");
            put(2, "一般");
            put(3, "很差");
            put(4, "失败");
        }};


        for (int i = 0;  i < monitorDiagnosisResultJsonArray.size(); i++) {
            JSONObject j = monitorDiagnosisResultJsonArray.getJSONObject(i);

            MonitorPointDiagnosisResultVo monitorDiagnosisResult = new MonitorPointDiagnosisResultVo();

            monitorDiagnosisResult.setApeId(j.getString("ape_id"))
                    .setPictureUrl(j.getString("picture_url"))
                    .setDiagnosisTime(j.getString("diagnosis_time"))
                    .setDiagnosisResult(j.getInteger("result"))
                    .setDiagnosisResultName(diagnosisResultDicMap.get(j.getInteger("result")))
                    .setDiagnosisResultReason(j.getString("diagnosis_result_reason"))
                    .setColorCast(j.getInteger("color_cast"))
                    .setColorCastName(videoDiagnosisDicMap.get(j.getInteger("color_cast")))
                    .setContrastRatio(j.getInteger("contrast_ratio"))
                    .setContrastRatioName(videoDiagnosisDicMap.get(j.getInteger("contrast_ratio")))
                    .setCrossStriation(j.getInteger("cross_striation"))
                    .setCrossStriationName(videoDiagnosisDicMap.get(j.getInteger("cross_striation")))
                    .setDefinition(j.getInteger("definition"))
                    .setDefinitionName(videoDiagnosisDicMap.get(j.getInteger("definition")))
                    .setFreeze(j.getInteger("freeze"))
                    .setFreezeName(videoDiagnosisDicMap.get(j.getInteger("freeze")))
                    .setHighLuminance(j.getInteger("high_luminance"))
                    .setHighLuminanceName(videoDiagnosisDicMap.get(j.getInteger("high_luminance")))
                    .setJitter(j.getInteger("jitter"))
                    .setJitterName(videoDiagnosisDicMap.get(j.getInteger("jitter")))
                    .setLoss(j.getInteger("loss"))
                    .setLossName(videoDiagnosisDicMap.get(j.getInteger("loss")))
                    .setLowLuminance(j.getInteger("low_luminance"))
                    .setLowLuminanceName(videoDiagnosisDicMap.get(j.getInteger("low_luminance")))
                    .setNoise(j.getInteger("noise"))
                    .setNoiseName(videoDiagnosisDicMap.get(j.getInteger("noise")))
                    .setOcclusion(j.getInteger("occlusion"))
                    .setOcclusionName(videoDiagnosisDicMap.get(j.getInteger("occlusion")))
                    .setRollingStripe(j.getInteger("rolling_stripe"))
                    .setRollingStripeName(videoDiagnosisDicMap.get(j.getInteger("rolling_stripe")))
                    .setSceneChange(j.getInteger("scene_change"))
                    .setSceneChangeName(videoDiagnosisDicMap.get(j.getInteger("scene_change")))
                    .setStripe(j.getInteger("stripe"))
                    .setStripeName(videoDiagnosisDicMap.get(j.getInteger("stripe")))
                    .setTransverseWave(j.getInteger("transverse_wave"))
                    .setTransverseWaveName(videoDiagnosisDicMap.get(j.getInteger("transverse_wave")));

            boolean isAddResult = true;
            for (String diagnosisItem : diagnosticItems) {
                HashSet set = (HashSet) param.get(diagnosisItem);
                if (!set.contains(j.getString(diagnosisItem))) {
                    isAddResult = false;
                }
            }
            if(!isAddResult) continue;
            res.add(monitorDiagnosisResult);
        }
        Collections.sort(res, (o1, o2) -> o2.getDiagnosisTime().compareTo(o1.getDiagnosisTime()));
        return res;
    }

    private HashMap<String, Object> setDiagnosisNodeSet(HashMap<String, Object> param) {
        for (String diagnosticItem : diagnosticItems) {
            String[] arr = new String[]{ "1", "2", "3", "4", "5"};
            String diagnosticItemVal = (String) param.get(diagnosticItem);
            if (diagnosticItemVal != null && diagnosticItemVal.length() != 0) {
                arr = diagnosticItemVal.split(",");
            }
            HashSet<String> set = new HashSet<>();
            Collections.addAll(set,arr);
            param.put(diagnosticItem, set);
        }
        return param;
    }
}
